package cn.edu.gzu.user.controller;

import cn.edu.gzu.user.entity.UserEntity;
import cn.edu.gzu.user.result.Result;
import cn.edu.gzu.user.result.ResultCode;
import cn.edu.gzu.user.service.UserService;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "bCryptPasswordEncoder")
    private PasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/signup")
    public JSONObject signup(@RequestBody UserEntity user) throws Exception {
        UserEntity user1 = userService.getOne(new QueryWrapper<UserEntity>().eq("username", user.getUsername()));
        if (user1 != null) {
           return Result.failure(ResultCode.FAILURE_REGISTERED_ERROR);
        }
        String pwd_bCrypt = bCryptPasswordEncoder.encode(user.getPassword());
        //String pwd_Base64 = Base64Util.encryptBASE64(user.getPassword().getBytes()); //Base64加密
        user.setPassword(pwd_bCrypt);
        userService.save(user);
        return Result.success("注册成功！");
    }

    @SneakyThrows
    @PostMapping("/login")
    public JSONObject login(@RequestBody UserEntity user) {
        System.out.println("前端参数:" + user.getUsername()+user.getPassword());
        UserEntity userdata = userService.getOne(new QueryWrapper<UserEntity>().eq("username", user.getUsername()));
        if (userdata == null) {
//            System.out.println("用户不存在！！");
            return Result.failure(ResultCode.FAILURE_USERNAME_OR_PASSWORD_ERROR);
        }
        //userdata.getPassword().equals(Base64Util.encryptBASE64(user.getPassword().getBytes())) Base64的比较条件
        if (bCryptPasswordEncoder.matches(user.getPassword(),userdata.getPassword())) {
            System.out.println("登录成功");
            return Result.success("登录成功！",userdata);
        }
        return Result.failure(ResultCode.FAILURE_USERNAME_OR_PASSWORD_ERROR);
    }


    @GetMapping("/info")
    public JSONObject getInfo(long id){
        System.out.println("获取用户"+id+"的信息中....");
        UserEntity user = userService.getById(id);
        if (user == null) {
            return Result.failure(ResultCode.FAILURE_QUERY_ERROR,"获取失败");
        }
        return Result.success("获取成功",user);
    }

   @GetMapping("/detail")
   public UserEntity getUserInfo(@RequestParam("id") long id){
        UserEntity user = userService.getById(id);
       if (user == null) {
           return null;
       }
       return user;
   }
}
